package com.yami.shop.api.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ijpay.unionpay.UnionPayApi;
import com.yami.shop.bean.app.param.PayParam;
import com.yami.shop.bean.app.param.PayXsCountOrderParam;
import com.yami.shop.bean.enums.PayEntry;
import com.yami.shop.bean.model.PayInfo;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.manager.impl.PayManager;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.PayInfoService;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Objects;

/**
 * @author LGH
 */
@Slf4j
@RestController
@RequestMapping("/p/order")
@Tag(name = "订单支付接口")
@AllArgsConstructor
public class PayController {

    private final PayInfoService payInfoService;
    private final UserService userService;
    private final PayManager payManager;
    private final ShopConfig shopConfig;

    @PostMapping("/pay")
    @Operation(summary =  "根据订单号进行支付", description = "根据订单号进行支付")
    @SneakyThrows
    public ServerResponseEntity<?> pay(HttpServletResponse httpResponse, @Valid @RequestBody PayParam payParam) {
        YamiUser user = SecurityUtils.getUser();
        String userId = user.getUserId();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.order.pay.user.disable"));
        }
        PayInfoDto payInfo = payInfoService.pay(userId, payParam);
        payInfo.setBizUserId(user.getBizUserId());
        payInfo.setPayType(payParam.getPayType());
        payInfo.setApiNoticeUrl("/notice/pay/" + PayEntry.ORDER.value() + "/" + payParam.getPayType());
        payInfo.setReturnUrl(payParam.getReturnUrl());
        payInfo.setUniUserId(ObjectUtil.isNotEmpty(payParam.getUniUserId()) ? payParam.getUniUserId() : null);
        // 付款方
        payInfo.setPayUserId(user.getXsUserId());

        payInfo.setBusinessType(ObjectUtil.isNotEmpty(payParam.getBusinessType()) ? payParam.getBusinessType() : null);
        payInfo.setReceiverGroupId(payParam.getReceiverGroupId());
        // 收款方 收款方ID 消费交易时，填收款方ID 担保交易时，填商户ID 默认担保交易
        payInfo.setReceiveUserId(payParam.getReceiveUserId());
        if(ObjectUtil.isNotEmpty(payParam.getBusinessType()) && payParam.getBusinessType().equals("04")){
            payInfo.setReceiveUserId(shopConfig.getHnaPay().getMerId());
        }
        // 如果是新生快捷支付则组装支付参数
        PayType payType = PayType.instance(payInfo.getPayType());
        if (Objects.equals(payType, PayType.HNAPAY_KJ)) {
            if(ObjectUtil.isNull(payParam.getXsFastPaymentOneParam())){
                throw new YamiShopBindException("yami.dtc.newborn.order.error");
            }
            if(Objects.isNull(payParam.getXsFastPaymentOneParam().getHolderName()) || Objects.isNull(payParam.getXsFastPaymentOneParam().getIdentityCode())){
                User userByUserId = userService.getUserByUserId(userId);
                payParam.getXsFastPaymentOneParam().setHolderName(userByUserId.getRealName());
                payParam.getXsFastPaymentOneParam().setIdentityCode(userByUserId.getIdNumber());
            }
        }
        payInfo.setXsFastPaymentOneParam(ObjectUtil.isNotEmpty(payParam.getXsFastPaymentOneParam()) ? payParam.getXsFastPaymentOneParam() : null);
        payInfo.setDivideAcctDtlList(ObjectUtil.isNotEmpty(payParam.getDivideAcctDtlList()) ? payParam.getDivideAcctDtlList() : null);
        payInfo.setPayUserType("0");
        return payManager.doPay(httpResponse, payInfo);
    }

    @PostMapping("/pay/xsCountOrder")
    @Operation(summary =  "根据新生订单号进行支付", description = "根据新生订单号进行支付，新生快捷支付第二步")
    @SneakyThrows
    public ServerResponseEntity<?> payXsCountOrder(HttpServletResponse httpResponse, @Valid @RequestBody PayXsCountOrderParam payXsCountOrderParam) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.order.pay.user.disable"));
        }
        if(ObjectUtil.isNull(payXsCountOrderParam.getXsFastPaymentTwoParam())){
            throw new YamiShopBindException("yami.dtc.newborn.order.error");
        }
        if (ObjectUtil.isNull(payXsCountOrderParam.getBusinessType()) ) {
            throw new YamiShopBindException("yami.dtc.newborn.parameter.empty");
        }
        PayInfo payInfo = payInfoService.getOne(new LambdaQueryWrapper<PayInfo>().eq(PayInfo::getPayNo, payXsCountOrderParam.getXsFastPaymentTwoParam().getPayNo()));
        ServerResponseEntity<?> serverResponseEntity = payManager.doHnaPayKjSen(payXsCountOrderParam,payInfo);
        log.info("根据新生订单号进行支付返回信息为{}", JSONUtil.toJsonStr(serverResponseEntity));
        return serverResponseEntity;
    }

    @GetMapping("/isPay/{payEntry}/{orderNumbers}")
    @Operation(summary =  "根据订单号查询该订单是否已经支付", description = "根据订单号查询该订单是否已经支付")
    @Parameter(name = "orderNumbers", description = "多个订单号拼接", required = true)
    public ServerResponseEntity<Boolean> isPay(@PathVariable Integer payEntry, @PathVariable String orderNumbers) {
        YamiUser user = SecurityUtils.getUser();
        Integer count = payInfoService.queryPay(orderNumbers, user.getUserId(), payEntry);
        boolean res = count != null && count == 1;
        return ServerResponseEntity.success(res);
    }

    @GetMapping( "/unionPayUserAuth")
    @Operation(summary =  "获取用户授权API", description = "获取用户授权API")
    public void unionPayUserAuth(HttpServletResponse response) throws IOException {
        String domainName = shopConfig.getDomain().getApiDomainName();
        String notifyUrl = domainName.concat("/notice/pay/callBack");
        String authUrl = UnionPayApi.buildAuthUrl(notifyUrl);
        response.sendRedirect(authUrl);
    }
}
